package com.web.exiaodao.remote.controller;
import com.web.exiaodao.business.entity.ExperienceTicket;
import com.web.exiaodao.business.entity.ExperienceTicketRecord;
import com.web.exiaodao.business.repository.ExperienceTicketRecordRepository;
import com.web.exiaodao.business.repository.ExperienceTicketRepository;
import com.web.exiaodao.business.repository.UserRepository;
import com.web.exiaodao.remote.service.ApiExperienceTicketRecordService;
import com.web.exiaodao.remote.service.ApiExperienceTicketService;
import com.web.exiaodao.remote.vo.ExperienceTicketRecordVo;
import com.web.exiaodao.remote.vo.ExperienceTicketVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.DateUtils;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 体验券（二期）接口
 * @Title: ApiExperienceTicketController.java
 * @Package com.web.exiaodao.remote.controller
 * @author wangxuemei  
 * @date 2016-12-30 下午2:58:03
 * @version V1.0
 */
@Api(value = "ExperienceTicket", description = "体验券（二期）接口", position = 10)
@Controller
@RequestMapping("/api/experienceTicket")
public class ApiExperienceTicketController extends BaseController {

	private static final Logger LOGGER = Logger.getLogger(ApiExperienceTicketController.class);

	@Autowired
	private ApiExperienceTicketService experienceTicketService;
	@Autowired
	private ApiExperienceTicketRecordService experienceTicketRecordService;
	@Autowired
	ExperienceTicketRepository experienceTicketRepository;
	@Autowired
	UserRepository userRepository;
	@Autowired
	ExperienceTicketRecordRepository experienceTicketRecordRepository;
	
	/**
	 * @Title: findExperienceTicketList
	 * @Description: 查询所有体验券（二期）信息
	 * @return    
	 */
	@ApiOperation(value="查询所有体验券（二期）",notes="查询所有体验券（二期）信息,当返回的code=1时，取出object进行显示,存放为数组对象")
	@ResponseBody
	@RequestMapping(value="findExperienceTicketList",method=RequestMethod.POST)
	public XaResult<List<ExperienceTicketVo>> findExperienceTicketList(
		@ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0", required = false) Integer nextPage,
		@ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10", required = false) Integer pageSize
	) throws BusinessException{
        XaResult<List<ExperienceTicketVo>> xr = new  XaResult<List<ExperienceTicketVo>>();
		Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, "[{property:'createTime',direction:'DESC'}]");
		Map<String , Object> filterParams =  WebUitl.getParametersStartingWith("{}", "search_");
		try{
				return experienceTicketService.findListEQStatusByFilter(XaConstant.Status.publish, filterParams, pageable);
		}catch(Exception e){
			if (e instanceof BusinessException) {
				xr.error(e.getMessage(), true);
			} else  {
				xr.error(XaConstant.Message.error, true);
			}
			LOGGER.error(XaConstant.Message.error, new Throwable(e));
		}
		return xr;
	}
	
	/**
	 * @Title: save
	 * @Description: 新增一条实体
	 * //@param userId
	 * //@param model
	 * @return    
	 */
	@ApiOperation(value="领取体验券",notes="供前端前期填充数据测试使用,上线后删除;新增体验券领取记录,当返回的code=1时，保存成功后object返回对象")
	@ResponseBody
	@RequestMapping(value="saveExperienceTicketRecord",method=RequestMethod.POST)
	public XaResult<ExperienceTicketRecordVo> saveExperienceTicketRecord(
		@ApiParam("用户id,字段名:userId") @RequestParam(value = "userId") Long userId,
		@ApiParam("体验券id,字段名:experienceTicketId") @RequestParam(value = "experienceTicketId") Long experienceTicketId,
		HttpServletRequest request
	) throws BusinessException{
		XaResult<ExperienceTicketRecordVo> xr = new XaResult<ExperienceTicketRecordVo>();
		try{
			if(XaUtil.isEmpty(userRepository.findOne(userId))){
				xr.error("该用户不存在");
				return xr;
			}
			ExperienceTicketRecord experienceTicketRecord  = experienceTicketRecordRepository.findByUserIdAndExperienceTicketIdAndStatusNot(userId, experienceTicketId, XaConstant.Status.delete);
			if(XaUtil.isNotEmpty(experienceTicketRecord)){
				xr.error("您已领取过该优惠券,不能重复领取");
				return xr;
			}
			ExperienceTicket obj = experienceTicketRepository.findOne(experienceTicketId);
			if(XaUtil.isEmpty(obj)){
				xr.error("该体验券不存在");
				return xr;
			}
			String expiration = obj.getExpirationDate();
			Date date1 = DateUtils.formatDateString2Date(expiration,"yyyy-MM-dd");
			if(date1.before(new Date())){
				xr.error("该体验券已过期");
				return xr;
			}
			
			ExperienceTicketRecord model = new ExperienceTicketRecord();
			model.setUserId(userId);
			model.setExperienceTicketId(experienceTicketId);
			return experienceTicketRecordService.createModel(model);
		}catch(Exception e){
 			if (e instanceof BusinessException) {
 			    xr.error(e.getMessage());
 			} else  {
 			    xr.error(XaConstant.Message.error);
 			}
 			LOGGER.error(XaConstant.Message.error, new Throwable(e));
		}
		return xr;
	}
	
}

